<?php

namespace App\Models;

use Illuminate\Support\Facades\DB;

/**
 * App\Models\GoodsCollect
 *
 * @property int $id
 * @property int|null $user_id 用户id
 * @property int|null $goods_id 商品id
 * @property \Illuminate\Support\Carbon|null $created_at
 * @property \Illuminate\Support\Carbon|null $updated_at
 * @method static \Illuminate\Database\Eloquent\Builder|GoodsCollect newModelQuery()
 * @method static \Illuminate\Database\Eloquent\Builder|GoodsCollect newQuery()
 * @method static \Illuminate\Database\Eloquent\Builder|GoodsCollect query()
 * @method static \Illuminate\Database\Eloquent\Builder|GoodsCollect whereCreatedAt($value)
 * @method static \Illuminate\Database\Eloquent\Builder|GoodsCollect whereGoodsId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|GoodsCollect whereId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|GoodsCollect whereUpdatedAt($value)
 * @method static \Illuminate\Database\Eloquent\Builder|GoodsCollect whereUserId($value)
 * @mixin \Eloquent
 */
class GoodsCollect extends Base
{
    protected $table = 'goods_collect';

    // 收藏
    static function collect($user_id, $goods_id)
    {
        $count = self::whereUserId($user_id)
            ->where('goods_id', $goods_id)
            ->count();
        if ($count > 0) return '商品已经收藏过了';

        try {
            DB::beginTransaction();

            $model = new self();
            $model->user_id = $user_id;
            $model->goods_id = $goods_id;
            $model->save();

            // 增加收藏数
            Goods::whereId($goods_id)->increment('collect_num');

            DB::commit();
            return true;
        } catch (\Exception $exception) {
            DB::rollBack();
        } catch (\Throwable $e) {
            DB::rollBack();
        }
        return false;
    }

    // 取消收藏
    static function unCollect($user_id, $goods_id)
    {
        $count = self::whereUserId($user_id)
            ->where('goods_id', $goods_id)
            ->count();
        if ($count == 0) return true;

        try {
            DB::beginTransaction();

            self::whereUserId($user_id)
                ->where('goods_id', $goods_id)
                ->delete();
            // 增加收藏数
            Goods::whereId($goods_id)->decrement('collect_num');

            DB::commit();
            return true;
        } catch (\Exception $exception) {
            DB::rollBack();
        } catch (\Throwable $e) {
            DB::rollBack();
        }
        return false;
    }
}
